<template>
  <view class="container">
    <view class="cropper-wrap">
      <image-cropper
        id="image-cropper"
        :zoom="0.5"
        :angle="0"
        :src="src"
        :disableCtrl="true"
        :disableRotate="true"
        canvasBackground="red"
        @cropped="cropped"
        @afterDraw="afterDraw"
        @beforeDraw="beforeDraw"
      />
    </view>
    <view class="btns">
      <button @tap="selectImg">
        {{ imagePath ? "重新上传" : "上传头像" }}
      </button>
      <button type="primary" @tap="confirm">确定</button>
    </view>
  </view>
</template>

<script>
import ImageCropper from "@/components/nice-cropper/cropper.vue";
export default {
  components: {
    ImageCropper,
  },
  data() {
    return {
      src: "",
      imagePath: null,
    };
  },
  onReady(){
	  this.selectImg();
  },
  methods: {
    selectImg() {
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        // sourceType: ["album", "camera"],
        success: (res) => {
          var tempFilePaths = res.tempFilePaths;
          this.src = tempFilePaths[0];
        },
      });
    },
    beforeDraw(context, transform) {
      context.setFillStyle("#fff");
      // transform.zoom = 1;
    },
    afterDraw(ctx, info) {
      var gradient = ctx.createLinearGradient(0, 0, 60, 0);
      gradient.addColorStop("0", "magenta");
      gradient.addColorStop("0.5", "blue");
      gradient.addColorStop("1.0", "red");
      // 用渐变填色
      ctx.fillStyle = gradient;
      // ctx.fillText("磕糖交友", 20, 20);
    },
    cropped(imagePath, imageInfo) {
      this.imagePath = imagePath;
    },
    confirm() {
      if (this.imagePath) {
        uni.$emit("uAvatarCropper", this.imagePath);
      }
      this.$u.route({
        type: "back",
      });
    },
  },
};
</script>

<style>
page {
  /* #ifdef MP-ALIPAY */
  position: absolute;
  width: 100%;
  /* #endif */
  height: 100%;
  /* border: 1px solid red; */
  box-sizing: border-box;
}
.container {
  height: 100%;
  /* display: flex; */
}

.btns {
  height: 120rpx;
}
.cropper-wrap {
  height: calc(100% - 170rpx);
}
</style>
